import { slice } from 'lodash';
var that; // 当前页面对象
var vk = uni.vk; // vk实例
export default {
    components: {},
    data() {
        return {
            watermarkText: '',
            watermarksPerPage: 12, // 每页水印数量
            page: {
                title: '报告打印',
                submitText: '确定',
                cancelText: '关闭',
                showCancel: true,
                top: '3vh',
                width: '806px'
            },
            form1: {},
            logourl: require('@/static/logo.png'),
            pageSzie: 22,
            pageSzie2: 53,
            pageSzie3: 84,
            pageSzie4: 115,
            pageSzie5: 146,
            onePageSize: 31,
            onePageHeight: 1200
        };
    },
    computed: {},
    mounted() {},
    activated() {},
    watch: {},
    methods: {
        // 初始化
        init() {
            //let { value } = that;

            //that.$emit("input", value);
        },
        handleImport() {
            this.$refs.file.click();
        },
        // 监听 - 页面打开
        onOpen() {
            that = this;
            let { item = {} } = that.value;
            that.form1.props.show = true;
        },
        // 监听 - 页面关闭
        onClose() {},
        // 监听 - 提交成功后
        onFormSuccess() {
            that.value.show = false; // 关闭页面
            that.$emit('success');
        },
        // 设置每页水印数量
        setWatermarksPerPage(count) {
            this.watermarksPerPage = count;
        },

        // 新增：判断是否应该显示页码
        shouldShowPageNumber(sampleCount) {
            // 第一页不显示页码
            if (sampleCount <= this.pageSzie) {
                return false;
            }

            // 特殊处理80个样品的情况
            if (sampleCount === 80) {
                // 第二页和第三页显示页码
                return true;
            }

            // 其他情况：如果样品数量超过第一页容量，显示页码
            return sampleCount > this.pageSzie;
        },

        // 新增：获取页码文本
        getPageNumberText(sampleCount) {
            // 特殊处理80个样品的情况
            if (sampleCount === 80) {
                // 根据当前渲染的页面返回对应的页码
                // 注意：这里需要根据实际渲染逻辑调整
                if (sampleCount > this.pageSzie && sampleCount <= this.pageSzie2) {
                    return '第二页';
                } else if (sampleCount > this.pageSzie2 && sampleCount <= this.pageSzie3) {
                    return '第三页';
                }
            }

            // 常规逻辑
            if (sampleCount > this.pageSzie && sampleCount <= this.pageSzie2) {
                return '第二页';
            } else if (sampleCount > this.pageSzie2 && sampleCount <= this.pageSzie3) {
                return '第三页';
            } else if (sampleCount > this.pageSzie3 && sampleCount <= this.pageSzie4) {
                return '第四页';
            } else if (sampleCount > this.pageSzie4) {
                return '第五页';
            }

            return '';
        },

        // 新增：判断是否是最后一页
        isLastPage(sampleCount) {
            // 特殊处理80个样品的情况
            if (sampleCount === 80) {
                // 只在第三页（最后一页）显示"报告完结"
                return sampleCount > this.pageSzie2 && sampleCount <= this.pageSzie3;
            }

            // 如果只有一页，那就是最后一页
            if (sampleCount <= this.pageSzie) {
                return true;
            }

            // 其他情况：根据样品数量判断是否是最后一页
            if (sampleCount > this.pageSzie4) {
                return true; // 第五页是最后一页
            } else if (sampleCount > this.pageSzie3 && sampleCount <= this.pageSzie4) {
                return true; // 第四页是最后一页
            } else if (sampleCount > this.pageSzie2 && sampleCount <= this.pageSzie3) {
                return true; // 第三页是最后一页
            } else if (sampleCount > this.pageSzie && sampleCount <= this.pageSzie2) {
                return true; // 第二页是最后一页
            }

            return false;
        },
        // 计算总页数
        calculateTotalPages() {
            let totalPages = 0;
            this.value.printData.forEach(v => {
                totalPages += this.getPageCount(v);
            });
            return totalPages || 1; // 至少返回1页
        },
        // 新的高级打印方法
        advancedPrint() {
            // 创建一个临时的iframe
            const iframe = document.createElement('iframe');
            iframe.style.display = 'none';
            document.body.appendChild(iframe);
            //   console.log(this.value.printData,'fsdfds')
            this.watermarkText = `HRP${vk.pubfn.timeFormat(this.value.printData[0].detect_time, 'yyyy年MM月dd日')}`;
            // 获取原始内容
            const contentElement = this.$refs.printContent;
            const contentHtml = contentElement.innerHTML;

            // 计算总页数
            const totalPages = this.calculateTotalPages();
            // 计算需要的水印总数
            const totalWatermarks = totalPages * this.watermarksPerPage;

            // 创建水印样式
            const watermarkStyle = `
                /* 页面样式 */
                @page {
                    margin: 1mm;
                    size: auto;
                }
                
                body {
                    margin: 0;
                    padding: 0;
                }
                
                /* 水印样式 */
                .watermark-container {
                    position: relative;
                    overflow: visible;
                }
                
                .watermark-fixed {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100vh;
                    pointer-events: none;
                    z-index: 1000;
                    page-break-before: always;
                }
                
                .watermark-page {
                    position: relative;
                    height: 100vh;
                    page-break-after: always;
                    page-break-inside: avoid;
                }
                
                .watermark-page:last-child {
                    page-break-after: auto;
                }
                
                .watermark-item {
                    position: absolute;
                    transform: rotate(-30deg);
                    opacity: 0.1;
                    font-size: 40px;
                    font-weight: bold;
                    color: #000;
                    white-space: nowrap;
                }

                /* 保留原有的打印样式 */
                .daying {border-spacing:0;width:100%;border-collapse:collapse;font-family:宋体;color:#000}
                .daying td {border:1px solid #000;height:15px}
                .daying td label {font-size:14px}
                .daying td span{font-size:16px}
            `;

            // 生成水印HTML
            // 使用CSS Grid创建更均匀的水印分布
            let watermarkHtml = `
                <style>
                    .watermark-overlay {
                        position: fixed;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        display: grid;
                        grid-template-columns: repeat(2, 1fr);
                        grid-template-rows: repeat(2, 1fr);
                        z-index: 999;
                        pointer-events: none;
                    }
                    
                    .watermark-cell {
                        display: flex;
                        justify-content: center;
                        align-items: center;
                    }
                    
                    .watermark-text {
                        transform: rotate(-30deg);
                        opacity: 0.1;
                        font-size: 40px;
                        font-weight: bold;
                        color: #000;
                        white-space: nowrap;
                    }
                    
                    @media print {
                        .watermark-overlay {
                            position: fixed !important;
                            top: 0 !important;
                            left: 0 !important;
                            width: 100% !important;
                            height: 100% !important;
                            -webkit-print-color-adjust: exact !important;
                            print-color-adjust: exact !important;
                        }
                        
                        .watermark-text {
                            -webkit-print-color-adjust: exact !important;
                            print-color-adjust: exact !important;
                        }
                    }
                </style>
                
                <div class="watermark-overlay">
                    <div class="watermark-cell">
                        <div class="watermark-text">${this.watermarkText}</div>
                    </div>
                    <div class="watermark-cell">
                        <div class="watermark-text">${this.watermarkText}</div>
                    </div>
                    <div class="watermark-cell">
                        <div class="watermark-text">${this.watermarkText}</div>
                    </div>
                    <div class="watermark-cell">
                        <div class="watermark-text">${this.watermarkText}</div>
                    </div>
                          <div class="watermark-cell">
                        <div class="watermark-text">${this.watermarkText}</div>
                    </div>
                          <div class="watermark-cell">
                        <div class="watermark-text">${this.watermarkText}</div>
                    </div>
                </div>
            `;

            // 修改HTML内容，确保最后一页不添加分页符
            const modifiedContentHtml = contentHtml.replace(/page-break-after:\s*always/g, 'page-break-after: auto');

            // 组合HTML
            const combinedHtml = `
                <html>
                    <head>
                        <style>
                            ${watermarkStyle}
                            @media print {
                                body { margin: 0; }
                                
                                /* 关键：确保水印在打印时可见 */
                                .watermark-overlay, .watermark-text {
                                    -webkit-print-color-adjust: exact !important;
                                    print-color-adjust: exact !important;
                                }
                                
                                /* 防止末尾空白页 */
                                html, body {
                                    height: auto !important;
                                }
                            }
                        </style>
                    </head>
                    <body>
                        ${watermarkHtml}
                        <div class="watermark-container">
                            ${modifiedContentHtml}
                        </div>
                    </body>
                </html>
            `;

            // 写入iframe
            const iframeDoc = iframe.contentWindow.document;
            iframeDoc.open();
            iframeDoc.write(combinedHtml);
            iframeDoc.close();

            // 等待iframe加载完成后打印
            setTimeout(() => {
                iframe.contentWindow.focus();
                iframe.contentWindow.print();

                // 打印完成后移除iframe
                setTimeout(() => {
                    document.body.removeChild(iframe);

                    // 更新打印计数（保留原有功能）
                    let _updateIds = this.value.printData.map(x => x._id);
                    vk.callFunction({
                        url: 'admin/testing/detection-form/sys/update_print_count',
                        data: {
                            _ids: _updateIds
                        },
                        success: data => {}
                    });
                }, 1000);
            }, 500);
        },
        //    print2() {
        //     // 添加打印样式，确保水印可见
        //     const printStyle = `
        //         @page {margin:1 1mm;font-size:7px}
        //         .daying {border-spacing:0;width:100%;border-collapse:collapse;font-family:宋体;color:#000}
        //         .daying td {border:1px solid #000;height:15px}
        //         .daying td label {font-size:14px}
        //         .daying td span{font-size:16px}

        //         /* 确保水印在打印时可见 */
        //         .watermark-layer {
        //             position: fixed !important;
        //             z-index: 9999 !important;
        //             opacity: 0.1 !important;
        //         }
        //         .watermark {
        //             -webkit-print-color-adjust: exact !important;
        //             color-adjust: exact !important;
        //             print-color-adjust: exact !important;
        //         }
        //     `;

        //     printJS({
        //         printable: `tableId-0`,
        //         type: 'html',
        //         style: printStyle,
        //         scanStyles: true,
        //         ignoreElements: [],
        //         properties: null
        //     });

        //     let _updateIds = this.value.printData.map(x => x._id);
        //     vk.callFunction({
        //         url: 'admin/testing/detection-form/sys/update_print_count',
        //         data: {
        //             _ids: _updateIds
        //         },
        //         success: data => {}
        //     });
        // },

        calcRowHeight(length) {
            // return length < 20 ? 30 : 20;
            return 26;
        },
        // 根据 sample_list 长度计算字体大小
        calcFontSize(length) {
            return 13;
            //  return length < 20 ? 14 : 10;
        },
        getsubList(list, index) {
            if (index == 1) {
                return list.slice(0, this.pageSzie);
            } else if (index == 2) {
                return slice(list, this.pageSzie, this.pageSzie2);
            } else if (index == 3) {
                return slice(list, this.pageSzie2, this.pageSzie3);
            } else if (index == 4) {
                return slice(list, this.pageSzie3, this.pageSzie4);
            } else if (index == 5) {
                return slice(list, this.pageSzie4, list.length);
            }
        },
        getSampleSatus(data) {
            let _result = '鲜样正常';

            if (vk.pubfn.isNotNull(data.sample_list)) {
                data.sample_list.forEach(element => {
                    if (vk.pubfn.isNotNull(element.yxresult)) {
                        if (element.yxresult != '阴性') {
                            _result = element.yxresult;
                            return _result;
                        }
                    }
                });
            }
            return _result;
        },
        getPageHeight(v) {
          
            let _height = this.onePageHeight;
            if (v.sample_list.length < this.pageSzie) {
                return _height;
            } else {
                _height = this.onePageHeight + this.onePageHeight * Math.ceil((v.sample_list.length - this.pageSzie) / (this.pageSzie * 1.5));
            }
            if (_height >= 4800) {
                _height=_height-50;
            }
                return _height;
        },
        getPageCount(v) {
            if (v.sample_list.length < this.pageSzie) {
                return 1;
            } else {
                return 1 + Math.ceil((v.sample_list.length - this.pageSzie) / (this.pageSzie * 1.5));
            }
        }
    }
};
